package com.tianyu.service.mqtt.common;

import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.util.StringUtils;

import jakarta.annotation.Resource;

/**
 *
 * @author swyan
 * @date 2021/11/10
 * @version 0.1
 */


@Configuration
public class MqttClientConfig {

    @Resource
    private MqttClientOptions mqttClientOptions;

    @Resource
    private Third01MqttClientOptions third01MqttClientOptions;

    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setServerURIs(mqttClientOptions.getUrls());
        mqttConnectOptions.setUserName(mqttClientOptions.getUsername());
        mqttConnectOptions.setPassword(StringUtils.hasText(mqttClientOptions.getPassword()) ?
                mqttClientOptions.getPassword().toCharArray() : new char[0]);
        mqttConnectOptions.setAutomaticReconnect(true);
        mqttConnectOptions.setKeepAliveInterval(10);
        factory.setConnectionOptions(mqttConnectOptions);
        return factory;
    }

    @Bean
    public MqttPahoClientFactory mqttThird01ClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setServerURIs(third01MqttClientOptions.getUrls());
        mqttConnectOptions.setUserName(third01MqttClientOptions.getUsername());
        mqttConnectOptions.setPassword(StringUtils.hasText(third01MqttClientOptions.getPassword()) ?
                third01MqttClientOptions.getPassword().toCharArray() : new char[0]);
        mqttConnectOptions.setAutomaticReconnect(true);
        mqttConnectOptions.setKeepAliveInterval(10);
        factory.setConnectionOptions(mqttConnectOptions);
        return factory;
    }
}
